package com.guli.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;

import com.guli.gulimall.product.dao.CategoryDao;
import com.guli.gulimall.product.entity.CategoryEntity;
import com.guli.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> treeList() {
        //三级分类树 1425
        List<CategoryEntity> allList=baseMapper.selectList(null);
        List<CategoryEntity> l1List=allList.stream().filter(item ->{

            return item.getParentCid().equals(0l);
        }).map(item ->{
          List<CategoryEntity> children=getChildren(allList,item);
          item.setChildren(children);
          return item;
        }).sorted((s1,s2)->{
            return (s1.getSort()!=null?s1.getSort():0)-(s2.getSort()!=null?s2.getSort():0);
        }).collect(Collectors.toList());

        return l1List;
    }

    private List<CategoryEntity> getChildren(List<CategoryEntity> allList, CategoryEntity categoryEntity) {
        List<CategoryEntity> children=allList.stream().filter(item ->{
            return item.getParentCid().equals(categoryEntity.getCatId());
        }).map(item ->{
            List<CategoryEntity> children1 = getChildren(allList, item);
            item.setChildren(children1);
            return item;
        }).sorted((s1,s2)->{
            return (s1.getSort()!=null?s1.getSort():0)-(s2.getSort()!=null?s2.getSort():0);
        }).collect(Collectors.toList());
        return children;
    }

}